package com.hh.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import javax.annotation.Resource;

@Slf4j
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * 允许访问的域名
     */
    @Value("${cors.allow-origin}")
    private String allowedOrigin;

    @Resource
    private WsHandshakeInterceptor wsHandshakeInterceptor;
    @Resource
    private CustomHandshakeHandler customHandshakeHandler;
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 启用简单的消息代理，用于广播和点对点消息
        config.enableSimpleBroker("/topic", "/queue");
        // 应用前缀，客户端发送消息的目标地址需要加这个前缀
        config.setApplicationDestinationPrefixes("/app");
        // 用户目标前缀，用于点对点消息
        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册WebSocket端点，客户端通过这个端点连接
        registry.addEndpoint("/ws")
                .addInterceptors(wsHandshakeInterceptor)
                .setHandshakeHandler(customHandshakeHandler)
                .setAllowedOriginPatterns("http://localhost:5173",allowedOrigin)  // 允许跨域
                .withSockJS();  // 启用SockJS，用于不支持WebSocket的浏览器
    }
}